package com.gjy.leetcode;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * 35. 搜索插入位置
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-03 16:11:44
 */
public class A35 {

    @Test
    public void test1() {
        int[] nums = {1, 3, 5, 6};
        int target = 5;
        assertEquals(2, search(nums, target));
    }

    @Test
    public void test2() {
        int[] nums = {1, 3, 5, 6};
        int target = 2;
        assertEquals(1, search(nums, target));
    }

    @Test
    public void tes3() {
        int[] nums = {1, 3, 5, 6};
        int target = 7;
        assertEquals(4, search(nums, target));
    }

    public int search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int m = l + (r - l) / 2;
            if (target > nums[m]) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        return l;
    }
}
